#include "stdafx.h"
#include "ChangeMultiBlankToOne.h"

ChangeMultiBlankToOne::ChangeMultiBlankToOne()
{
}

ChangeMultiBlankToOne::~ChangeMultiBlankToOne()
{
}

bool ChangeMultiBlankToOne::FindBlankStartPos(int ids, int& idBlankStart, int& idBlankEnd)
{
	idBlankStart = -1;
	idBlankEnd = -1;
	bool bFindS = false;

	int num = m_csReadlines.GetSize();
	for (int k = ids; k < num; k++)
	{
		CString string0 = m_csReadlines[k];
		CString string = string0;
		string.Trim();
		if (string == _T(""))
		{
			idBlankStart = k;
			idBlankEnd = k + 1;
			bFindS = true;
			m_csNewFileLines.push_back(string0);
			break;
		}

		m_csNewFileLines.push_back(string0);
	}

	if (bFindS)
	{
		for (int k = idBlankStart; k < num; k++)
		{
			CString string = m_csReadlines[k];
			string.Trim();
			if (string != _T(""))
			{
				idBlankEnd = k;
				break;
			}
		}
	}

	if (idBlankStart != -1) return true;

	return false;
}

void ChangeMultiBlankToOne::DeleteFunction(CString fileName, CString csFunction)
{
	PublicFunc::ReadSourceFile(fileName, m_csReadlines);

	m_csNewFileLines.clear();

	int ids = 0;
	int idBlankStart, idBlankEnd;
	while (ids<m_csReadlines.GetSize())
	{
		FindBlankStartPos(ids, idBlankStart, idBlankEnd);
		ids = idBlankEnd;
		if (ids == -1) return;
	}

	CFileFind finder;
	BOOL bResult = finder.FindFile(fileName);
	if (bResult)
	{
		DeleteFile(fileName);
	}
	try
	{
		CString str;
		CStdioFile file(fileName, CFile::modeCreate | CFile::modeWrite);			file.SetLength(0);

		int len = m_csNewFileLines.size();
		for (int i = 0; i < len; i++)
		{
			CString string = m_csNewFileLines[i];
			file.WriteString(string);

			if (i != len - 1)
			file.WriteString("\n");
		}

		file.Close();
	}
	catch (CFileException* e)
	{
		e->ReportError();
		e->Delete();

		return;
	}
}

bool ChangeMultiBlankToOne::Do(CString fileName)
{
	DeleteFunction(fileName, _T("::dataIn(DcDataFiler"));

	return true;
}

bool ChangeMultiBlankToOne::IsFileValid(CString fileName)
{
	int id = fileName.ReverseFind('.');
	int len = fileName.GetLength();
	CString csExt = fileName.Mid(id + 1, len - id - 1);

	if (csExt == _T("cpp") || csExt == _T("h")) return true;

	return false;
}
